﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Security.AccessControl;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;
using System.Web.UI;
using yao.Common;
using yao.Entity;
using Titan;
using yao.website.Models;

namespace yao.website.Controllers
{
    /// <summary>
    /// 注册
    /// </summary>
    public class RegistController : BaseController
    {
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Index(CompanyRegister companyRegister)
        {
            #region 验证

            Validate(companyRegister, CompanyRegister_.LoginNo, CompanyRegister_.Mb);
            LIsNullEmpty("Password", companyRegister.Password, "密码不能为空");
            LIsNullEmpty("CheckCode", Request["CheckCode"], "短信验证码不能为空");
            LStrEquals("CheckCode", Request["CheckCode"], Session["MbValidateCode"]+"", "短信验证码错误");
            #endregion

            if (IsValid)
            {
                return View("Company", companyRegister);
            }
            return View();
        }

        [HttpPost]
        public ActionResult SendCode(string mb)
        {
            Random random = new Random((int)DateTime.Now.Ticks);
            string code = random.Next(100000, 999999).ToString();
            code = "123456"; //测试时用123456
            Session["MbValidateCode"] = code;
            //Response.SetCookie("ValidateCode", 123456);
            return Json(new { code = 1 });
        }

        public ActionResult Company(CompanyRegister companyRegister)
        {
            return View();
        }

        [HttpPost]
        public ActionResult Complete(CompanyRegister companyRegister)
        {
            Validate(companyRegister, CompanyRegister_.CompanyName);
            if (!ModelState.IsValid)
            {
                return View("Company", companyRegister);
            }
            companyRegister.Ip = CommonFun.GetIpAddress();
            companyRegister.CreateTime = DateTime.Now;
            companyRegister.AuditStateId = 1;
            using (IDbSession cn = OpenSession())
            {
                if (cn.Insert(companyRegister) > 0)
                {
                    return RedirectToAction("Success");
                }
            }
            return View("Company", companyRegister);
        }

        public ActionResult Success()
        {
            return View();
        }

        public ActionResult ForgetPassword()
        {
            ForgetPassword forgetPassword = new ForgetPassword();
            return View(forgetPassword);
        }
        [HttpPost]
        public ActionResult ForgetPassword(ForgetPassword forgetPassword)
        {
            //判断验证码
            if (string.IsNullOrWhiteSpace(forgetPassword.ValidateCode) || Session["MbValidateCode"] as string != forgetPassword.ValidateCode)
            {
                AddPageError("验证码错误");
                return View(forgetPassword);
            }
            //先检查用户名和手机是否匹配
            using (IDbSession cn = OpenSession())
            {
                QueryExpression q = new QueryExpression();
                q.EntityType = typeof(Employee);
                q.Selects.Add(Employee_.IsActive);//employee是否禁用 
                q.Selects.Add(Employee_.EmployeeId);
                q.Selects.Add(Employee_.Mb);
                //q.Selects.Add(Employee_.EmployeeName);
                //q.Selects.Add(Employee_.CompanyId);
                q.Selects.Add(Employee_.Company.IsActive);//公司是否禁用
                //q.Selects.Add(Employee_.Company.CompanyCode);
                //q.Selects.Add(Employee_.Company.CompanyName);
                //q.Selects.Add(Employee_.Company.AreaId);
                q.Wheres.Add(Employee_.LoginNo.TEqual(forgetPassword.LoginNo));
                Employees employees = new Employees();
                cn.SelectCollection(employees.Items, q);
                if (employees.Items.Count <= 0)
                {
                    AddPageError("用户名或手机号码错误，请重试");
                    return View(forgetPassword);
                }
                Employee dbEmployee = employees.Items[0];
                dbEmployee.Mb = Encryption.Decrypt(dbEmployee.Mb, forgetPassword.LoginNo);
                if (dbEmployee.Mb != forgetPassword.Mb)
                {
                    AddPageError("用户名或手机号码错误，请重试");
                    return View(forgetPassword);
                }
                if (!dbEmployee.IsActive)
                {
                    AddPageError("用户已被禁用，请与贵公司系统管理员联系");
                    return View(forgetPassword);
                }
                if (!dbEmployee.Company.IsActive)
                {
                    AddPageError("公司账户已停用，请尽快与我们联系");
                    return View(forgetPassword);
                }
                //此时已经正确

                Session.Remove("MbValidateCode");
                Session["FindPassword_EmployeeId"] = dbEmployee.EmployeeId;
                //Session["FindPassword_Mb"]=forgetPassword.Mb;

                string redirect = "/Regist/ResetPassword";
                return Redirect(redirect);
            } 
        }
        //public ActionResult ForgetPasswordCheck()
        //{
        //    if (Session["FindPassword_EmployeeId"] == null) return Redirect("/Regist/ForgetPassword");
        //    //需要发送手机验证码
        //    Random random=new Random((int)DateTime.Now.Ticks) ;
        //    string code = random.Next(100000, 999999).ToString();
        //    Session["ValidateCode"] = code;
        //    CommonFun.SendSms(Session["FindPassword_Mb"] + "", "您的验证码为："+code);
        //    ForgetPassword forgetPassword = new ForgetPassword();
        //    return View(forgetPassword);
        //}
        //[HttpPost]
        //public ActionResult ForgetPasswordCheck(ForgetPassword forgetPassword)
        //{
        //    if (Session["FindPassword_EmployeeId"] == null) return Redirect("/Regist/ForgetPassword");
        //    //判断验证码
        //    if (string.IsNullOrWhiteSpace(forgetPassword.MbValidateCode) || Session["ValidateCode"] as string != forgetPassword.MbValidateCode)
        //    {
        //        AddPageError("验证码错误");
        //        return View(forgetPassword);
        //    }
        //    //此时已经正确
        //    Session.Remove("ValidateCode");
        //    Session.Remove("FindPassword_Mb");
        //    string redirect = "/Regist/ResetPassword";
        //    return Redirect(redirect);
        //}

        public ActionResult ResetPassword()
        {
            if (Session["FindPassword_EmployeeId"] == null) return Redirect("/Regist/ForgetPassword");
            ResetPassword resetPassword = new ResetPassword();
            return View(resetPassword);
        }

        [HttpPost]
        public ActionResult ResetPassword(ResetPassword resetPassword)
        {
            if (Session["FindPassword_EmployeeId"] == null) return Redirect("/Regist/ForgetPassword");
            resetPassword.Password = (resetPassword.Password + "").ToLower();
            resetPassword.Password2 = (resetPassword.Password2 + "").ToLower();
            Validate(resetPassword, "Password");
            Validate(resetPassword, "Password2");
            if (resetPassword.Password != resetPassword.Password2)
            {
                AddPageError("两次输入的密码不同，请重新输入");
            }
            if (IsValid)
            {
                using (IDbSession cn = OpenSession())
                {
                    Employee employee = new Employee();
                    employee.EmployeeId = (long)Session["FindPassword_EmployeeId"];
                    employee.Password = Encryption.GetMD5HashHex(resetPassword.Password);
                    cn.Update(employee, Employee_.Password);
                }
                Session.Remove("FindPassword_EmployeeId"); 
                string redirect = "/Regist/ResetPasswordOk";
                return Redirect(redirect);
            }
            return View(resetPassword);
        }

        public ActionResult ResetPasswordOk()
        { 
            return View();
        }
    }
}
